<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.merchant_name" placeholder="商户名称" style="width: 130px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.province" placeholder="请选择省份" filterable class="filter-item" style="width: 130px;" @change="changeRegionProvince">
        <el-option v-for="(province,index) in this.merchant_province" :label="province.name" :value="province.region_id":key="index" />
      </el-select>
      <el-select v-model="listQuery.city" placeholder="请选择城市" filterable class="filter-item" style="width: 130px;" >
        <el-option v-for="(city,index) in this.merchant_city" :label="city.name" :value="city.region_id":key="index" />
      </el-select>
      <el-select v-model="listQuery.feed" placeholder="海尔反馈" filterable class="filter-item" style="width: 180px;" >
        <el-option v-for="(item,index) in this.schedule_conditon.feed" :label="item.name" :value="item.id":key="index" />
      </el-select>
      <el-select v-model="listQuery.app" placeholder="审核状态" filterable class="filter-item" style="width: 180px;" >
        <el-option v-for="(item,index) in this.schedule_conditon.app" :label="item.name" :value="item.id":key="index" />
      </el-select>
      <el-select v-model="listQuery.sign" placeholder="签约状态" filterable class="filter-item" style="width: 180px;" >
        <el-option v-for="(item,index) in this.schedule_conditon.sign" :label="item.name" :value="item.id":key="index" />
      </el-select>
      <el-select v-model="listQuery.xr" placeholder="进度" filterable class="filter-item" style="width: 180px;" >
        <el-option v-for="(item,index) in this.schedule_conditon.xr" :label="item.name" :value="item.id":key="index" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"  @click="excelout">导出</el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <excel style="margin-top: 0px;"></excel>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini"  border fit highlight-current-row style="width: 100%;">
      <el-table-column label="商户名称" align="center" width="300">
        <template slot-scope="{row}">
          <span>{{ row.merchant_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="省" align="center"  width="80">
        <template slot-scope="{row}">
          <span>{{ row.province_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="市" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.city_name }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="海尔反馈" align="center" width="240">
        <template slot-scope="{row}">
          <span>{{ row.feed_name }}</span>
        </template>
      </el-table-column>

      
      <el-table-column label="审批状态" align="center"  width="200">
        <template slot-scope="{row}">
          <span>{{ row.approval_status_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签约状态" align="center"   width="200">
        <template slot-scope="{row}">
          <span>{{ row.sign_status_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售进度" align="center"   width="120">
        <template slot-scope="{row}">
          <span>{{ row.xr_schedule_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同寄回时间" align="center"   width="100">
        <template slot-scope="{row}">
          <span>{{ row.contract_backdate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同邮寄云贷" align="center"   width="100">
        <template slot-scope="{row}">
          <span>{{ row.contract_tohaier_date }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center"  >
        <template slot-scope="{row}">
          <span>{{ row.desc }}</span>
        </template>
      </el-table-column>
   
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" >
        <template slot-scope="{row,$index}">
          <el-dropdown :hide-on-click="false" >
            <span class="el-dropdown-link" style="color:#67C23A">
              更多操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button type="primary" size="mini" @click="handleUpdate(row)"  v-if="nodes.indexOf('158')!=-1">
                  编辑信息
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                 <el-button size="mini" type="info"  @click="showLog(row.id)">
                  操作日志
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

      
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="商户进度" :visible.sync="dialogFormVisible" width="660px" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 60%; margin-left:70px;">
        <el-form-item label="商户名称" prop="merchant_name">
          <el-input v-model="temp.merchant_name" type="text" placeholder="请输入企业名称" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="所在省份" prop="province">
          <el-select v-model="temp.province" placeholder="请选择省份" filterable @change="changeRegionProvince">
            <el-option v-for="(province,index) in this.merchant_province" :label="province.name" :value="province.region_id"
              :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-select v-model="temp.city" placeholder="请选择市" filterable >
            <el-option v-for="(city,index) in this.merchant_city" :label="city.name" :value="city.region_id" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="海尔反馈" prop="haier_feedback">
          <el-select v-model="temp.haier_feedback" placeholder="请选择" filterable >
            <el-option v-for="(item,index) in this.schedule_conditon.feed" :label="item.name" :value="item.id" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="approval_status">
          <el-select v-model="temp.approval_status" placeholder="请选择" filterable >
            <el-option v-for="(item,index) in this.schedule_conditon.app" :label="item.name" :value="item.id" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="签约状态" prop="sign_status">
          <el-select v-model="temp.sign_status" placeholder="请选择" filterable >
            <el-option v-for="(item,index) in this.schedule_conditon.sign" :label="item.name" :value="item.id" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度" prop="xr_schedule">
          <el-select v-model="temp.xr_schedule" placeholder="请选择" filterable >
            <el-option v-for="(item,index) in this.schedule_conditon.xr" :label="item.name" :value="item.id" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同寄回时间" prop="contract_backdate">
          <el-date-picker type="date" placeholder="选择日期" v-model="temp.contract_backdate" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="合同邮寄云贷" prop="contract_tohaier_date">
          <el-date-picker type="date" placeholder="选择日期" v-model="temp.contract_tohaier_date" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input v-model="temp.desc" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="merchantScheduleCreateOrUpdate()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogRecordAble" class="abow_dialog" title="操作日志"  width="750px" >
      <div class="block">
        <el-timeline :reverse="true">
          <el-timeline-item
            v-for="(item, index) in logList"
            :key="index"
            :timestamp="item.time">
            <div class="collectcss" >操作人员：<span>{{item.admin}}</span></div>
            <div class="collectcss" v-for="(v,k) in item.log" :key="k"><span>{{v}}</span></div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>  
  </div>
</template>

<script>
  import {
    merchantScheduleConditon,
    fetchMerchantRegion,
    fetchMerchantScheduleList,
    merchantScheduleCreateOrUpdate,
    fetchMerchantBase,
    showMerchantScheduleLog,
    exceloutMerchantSchedule
  } from '@/api/merchant'
  import excel from '@/components/excelout/index.vue'
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime,getNodes
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: {
      Pagination,excel
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          0: 'danger'
        }
        return statusMap[status]
      },
      statusNameFilter(status) {
        const statusNameMap = {
          1: '启用',
          0: '禁用'
        }
        return statusNameMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        logList:[],
        dialogRecordAble:false,
        diff:{},
        olddata:{},
        schedule_conditon:[],
        activeName:'1',
        action: process.env.VUE_APP_BASE_API + '/backend_upload',
        myHeaders: {
          token: this.$store.getters.token
        },
        tableKey: 0,
        nodes:[],
        limit: 1,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          merchant_name: '',
        },
        merchant_province: [],
        merchant_city: [],
        merchant_district: [],
        tempCheck: {
          level_id: '',
          is_checked: 1,
          merchant_id: ''
        },
        temp:{},
       
        data: {
          third_platform: []
        },
        dialogCheckVisible: false,
        dialogFormVisible:false,
        rules: {
          merchant_name: [{
            required: true,
            message: '商户名称必须填写',
            trigger: 'change'
          }],
          province: [{
            required: true,
            message: '省份必须选择',
            trigger: 'change'
          }],
          city: [{
            required: true,
            message: '城市必须选择',
            trigger: 'change'
          }], 
        },
        downloadLoading: false
      }
    },
    created() {
      this.listQuery.merchant_id = this.$route.params.merchant_id
      this.cacheQueryFormat();
      this.getList();
      this.nodes = getNodes();
      this.merchantScheduleConditon();
      this.getRegion();
      //添加钩子，页面刷新
      window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    destroyed() {
      //添加钩子，页面刷新
      window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
    },
    methods: {
      showLog(id){
        this.logList = [];
        
        showMerchantScheduleLog({flow_id:id}).then(response => {
          if(response.data.length==0){
            this.$notify({
                  title: 'error',
                  message: '暂无数据！',
                  type: 'error',
                  duration: 2000
                })
                this.dialogRecordAble = false;
          }else{
            this.dialogRecordAble = true;
            this.logList = response.data;
          }
          
        })
      },
      excelout() {
        this.listLoading = true
        this.listQuery.page = 1
        this.listQuery.limit = this.total
        exceloutMerchantSchedule(this.listQuery).then(response => {
          this.listLoading = false
          const filepath = response.data.path
          window.location.href = filepath
        })
      },
      beforeunloadFn(e) {
        //刷新页面事件
        sessionStorage.removeItem('merchantHaierSchedudleList');
      },
      cacheQueryFormat(){
        let cacheQuery = sessionStorage.getItem('merchantHaierSchedudleList');
        if(cacheQuery){
          this.listQuery = JSON.parse(cacheQuery);
        }
      },
      getList() {
        sessionStorage.setItem('merchantHaierSchedudleList',JSON.stringify(this.listQuery))
        this.listLoading = true
        fetchMerchantScheduleList(this.listQuery).then(response => {
          this.list = response.data.data
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
      merchantScheduleConditon() {
        merchantScheduleConditon().then(response => {
          this.schedule_conditon = response.data;
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      changeRegionProvince(val) {
        let pam = {pid:val};
        fetchMerchantRegion(pam).then(res => {
          this.merchant_city = res.data
        })
      },
      handleCreate(){
        this.dialogFormVisible = true;
        this.temp = {};
        this.olddata = {};
      },
      handleUpdate(row) {
        this.dialogFormVisible = true;
        this.temp = row;
        //保留原数据
        this.olddata.id = row.id;
        this.olddata.merchant_name = row.merchant_name;
        this.olddata.province = row.province;
        this.olddata.city = row.city;
        this.olddata.haier_feedback = row.haier_feedback;
        this.olddata.approval_status = row.approval_status;
        this.olddata.sign_status = row.sign_status;
        this.olddata.xr_schedule = row.xr_schedule;
        this.olddata.contract_backdate = row.contract_backdate;
        this.olddata.contract_tohaier_date = row.contract_tohaier_date;
        this.olddata.desc = row.desc;

        this.changeRegionProvince(row.province);
      },
      getRegion(){
        fetchMerchantBase().then(res => {
          this.merchant_province = res.data.province
        });
      },
      //提交
      merchantScheduleCreateOrUpdate(){
   
        this.$refs['dataForm'].validate((valid) => {
          if(this.temp.id){
            for (const k in this.olddata) {
              if (this.olddata[k] != this.temp[k]) {
                this.diff[k] = this.temp[k]
              }
            }
            this.diff.id = this.temp.id
          }else{
            this.diff = this.temp;
          }
          if (valid) {
            merchantScheduleCreateOrUpdate(this.diff).then(res => {
              if(res.code==200){
                this.dialogFormVisible = false;
                this.$notify({
                  title: 'success',
                  message: '成功！',
                  type: 'success',
                  duration: 2000,
                  onClose: this.getList()
                })
              }
            });
          }
        })
        
      },
      ///
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
<style>
.collectcss{margin-top:7px;color:#999;font-size:14px}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    float: left;
  }
</style>
